#include "mainwindow.h"
#include "./ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this-> setWindowTitle("My Application");


    //初始化、创建菜单栏
    QMenuBar *menuBar = new QMenuBar(this);
    this->setMenuBar(menuBar);

    QMenu *fileMenu = new QMenu("File", this);
    menuBar->addMenu(fileMenu);

    QAction *openAction = new QAction("Open", this);
    fileMenu->addAction(openAction);

    QAction *saveAction = new QAction("Save", this);
    fileMenu->addAction(saveAction);

    QAction *exitAction = new QAction("Exit", this);
    fileMenu->addAction(exitAction);

    //创建中央控件
    edit = new QTextEdit(this);
    this->setCentralWidget(edit);
    edit->setPlaceholderText("在此处编写文本内容....");

    connect(openAction, &QAction::triggered, this, &MainWindow::open);
    connect(saveAction, &QAction::triggered, this, &MainWindow::save);
    connect(exitAction, &QAction::triggered, this, &MainWindow::exit);
}

void MainWindow::open()
{
    // QString fileName = QFileDialog::getOpenFileName(this, "Open File", "", "Text Files (*.txt);;All Files (*)");
    // if (!fileName.isEmpty()) {
    //     QFile file(fileName);
    //     qDebug()<<"filename："<<fileName;
    //     if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    //         QTextStream in(&file);
    //         edit->setPlainText(in.readAll());
    //         file.close();
    //     }
    // }

    // 弹出对话框, 选择打开的文件
    QFileDialog* dialog = new QFileDialog(this);
    QString fileName = dialog->getOpenFileName(this, "open file", "", "Text Files (*.txt);;All Files (*)");
    qDebug() << "fileName: " << fileName;
    // 读取文件
    std::ifstream file(fileName.toStdString().c_str());
    if (!file.is_open()) {
        qDebug() << "⽂件加载失败!";
        return;
    }
    std::string content;
    std::string line;
    while (std::getline(file, line)) {
        content += line;
        content += "\n";
    }
    file.close();
    // 显示到界面上
    QString text = QString::fromStdString(content);
    edit->setPlainText(text);
}

void MainWindow::save(){
    QFileDialog* dialog = new QFileDialog(this);
    QString fileName = dialog->getSaveFileName(this, "Save File", "", "Text Files (*.txt);;All Files (*)");
    qDebug() <<"filename：" <<fileName;

    //写入文件
    std::ofstream file(fileName.toStdString().c_str());
    if(!file.is_open()){
        qDebug()<<"文件打开失败";
        return;
    };
    const QString& text = edit->toPlainText();
    file << text.toStdString();
    file.close();
}

void MainWindow::exit(){
    this->close();
}

void MainWindow::load(){

}

MainWindow::~MainWindow()
{
    delete ui;
}
